package com.tuling.controller;

import com.tuling.domain.Cart;
import com.tuling.domain.Fruit;
import com.tuling.service.CartService;
import com.tuling.service.CartServiceImpl;
import com.tuling.service.FruitService;
import com.tuling.service.FruitServiceImpl;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.util.List;

@WebServlet(name = "fruitServlet", value = "/fruitServlet")
public class FruitServlet extends HttpServlet {
    private FruitService fruitService = new FruitServiceImpl();
    private CartService cartService = new CartServiceImpl();
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 获取参数
        String method = request.getParameter("method");
        // 根据method做不同处理
        if (method.equals("hot")) {
            // 热卖列表
            hot(request, response);
        } else if (method.equals("info")) {
            // 查询水果详情
            info(request, response);
        }
    }

    private void info(HttpServletRequest request, HttpServletResponse response) {
        // 获取参数
        String fidStr = request.getParameter("fid");
        int fid = Integer.parseInt(fidStr);
        // 调用业务逻辑层
        Fruit byId = fruitService.findById(fid);
        request.setAttribute("fruit", byId);
        hot(request, response);

        String uidStr = request.getParameter("uid");
        int uid = Integer.parseInt(uidStr);
        if (0 != uid) {
            Cart cart = cartService.find(uid, fid);
            if (cart != null) {
                if (cart.getIsCart()) {
                    request.setAttribute("tit1", "已加入购物车");
                }
                if (cart.getIsStar()) {
                    request.setAttribute("tit2", "已关注");
                }
            }
        }

        // 转发到水果页面详情
        try {
            request.getRequestDispatcher("/fruit_info.jsp").forward(request, response);
        } catch (ServletException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void hot(HttpServletRequest request, HttpServletResponse response) {
        List<Fruit> hot = fruitService.findHot();
        request.setAttribute("fruits", hot);
    }
}
